<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="icon" href="/static/images/x.ico">
    <title>成语猜谜 </title>
    <link rel="stylesheet" href="{{ url_for('static', filename='css/styles.css') }}">
    <link rel="stylesheet" href="{{ url_for('static', filename='css/sweetalert2.min.css') }}">
</head>
<body>
    <div class="container">
        <div class="loader">
            <div class="spinner"></div>
        </div>
        
<div class="title-container">
  <img src="/static/images/03.png" alt="灯笼图标" class="title-icon" >
  <h1 class="title-title">🎋 成语猜谜 🏮  </h1>
</div>
        <div class="progress-bar">
            <div class="progress" style="width: {{ ((current_index + 1) / total_riddles) * 100 }}%"></div>
        </div>
        <div class="score-board">
            当前得分：{{ score }} | 进度：{{ current_index + 1 }}/{{ total_riddles }}
        </div>

        <div class="riddle-container">
            <img 
                src="{{ url_for('static', filename='riddles/' + riddle.image) }}" 
                alt="灯谜图片" 
                class="riddle-image"
                loading="lazy"
            >
        </div>

        <div class="input-group">
            <input 
                type="text" 
                id="answer" 
                placeholder="请输入四字成语..."
                autocomplete="off"
                enterkeyhint="go"
            >
            <button type="submit" onclick="checkAnswer(event)">提交答案</button>
            <button id="actionBtn" onclick="handleAction()">
                {{ '下一题 ➔' if current_index < total_riddles - 1 else '最终提交 🎉' }}
            </button>
        </div>
    </div>

    <script src="{{ url_for('static', filename='js/sweetalert2.all.min.js') }}"></script>
    <script>
        let isLoading = false;
        let errorCount = 0;
        const total = {{ total_riddles }};

        // 初始化按钮功能
        function updateButtonFunction(currentIndex) {
            const actionBtn = document.getElementById('actionBtn');
            if (currentIndex >= total - 1) {
                actionBtn.textContent = '最终提交 🎉';
                actionBtn.onclick = submitGame;
            } else {
                actionBtn.textContent = '下一题 ➔';
                actionBtn.onclick = loadNextQuestion;
            }
        }
        updateButtonFunction({{ current_index }});

        // 显示加载动画
        function showLoader() {
            document.querySelector('.loader').style.display = 'flex';
            isLoading = true;
        }

        // 隐藏加载动画
        function hideLoader() {
            document.querySelector('.loader').style.display = 'none';
            isLoading = false;
        }

        // 答案验证
        async function checkAnswer(event) {
            event.preventDefault();
            if(isLoading) return;
            
            const answer = document.getElementById('answer').value.trim();
            if (!answer) {
                await Swal.fire({
                    icon: 'warning',
                    title: '提示',
                    text: '请输入答案',
                    timer: 2000,
                    showConfirmButton: false
                });
                return;
            }

            showLoader();
            try {
                const response = await fetch('/check_answer', {
                    method: 'POST',
                    headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                    body: `answer=${encodeURIComponent(answer)}`
                });
                
                const data = await response.json();
                document.querySelector('.score-board').textContent = 
                    `当前得分：${data.score} | 进度：${data.current_index + 1}/${data.total_riddles}`;
                document.querySelector('.progress').style.width = 
                    `${((data.current_index + 1) / data.total_riddles) * 100}%`;

                if(data.correct) {
                    errorCount = 0;
                    await Swal.fire({
                        icon: 'success',
                        title: '🎉 回答正确！',
                        html: '<span style="color: #2ecc71;">+10 分</span>',
                        showConfirmButton: false,
                        timer: 2500
                    });
                } else {
                    errorCount++;
                    let errorHtml = errorCount >= 2 ? `正确答案是：<b>${data.correct_answer}</b>` : '请再试一次';
                    if (errorCount >= 2) {
                        errorCount = 0;
                    }
                    await Swal.fire({
                        icon: 'error',
                        title: '😅 再接再厉',
                        html: errorHtml,
                        showConfirmButton: false,
                        timer: 3500
                    });
                }
            } catch (error) {
                await Swal.fire('错误', '提交答案失败', 'error');
            } finally {
                hideLoader();
                document.getElementById('answer').value = '';
            }
        }

        // 加载下一题
        async function loadNextQuestion() {
            if(isLoading) return;
            showLoader();
            try {
                const response = await fetch('/next_question', {
                    method: 'POST',
                    headers: {'Content-Type': 'application/x-www-form-urlencoded'}
                });
                const data = await response.json();
                
                document.querySelector('.riddle-image').src = data.image_url;
                document.querySelector('.score-board').textContent = 
                    `当前得分：${data.score} | 进度：${data.current_index + 1}/${data.total_riddles}`;
                document.querySelector('.progress').style.width = 
                    `${((data.current_index + 1) / data.total_riddles) * 100}%`;

                updateButtonFunction(data.current_index);
            } catch (error) {
                await Swal.fire('错误', error.message, 'error');
            } finally {
                hideLoader();
            }
        }

        // 提交游戏
        async function submitGame() {
            showLoader();
            try {
                const response = await fetch('/submit', { 
                    method: 'POST' 
                });
                const data = await response.json();
                window.location.href = `/finish?score=${data.score}`;
            } catch (error) {
                await Swal.fire('错误', '提交失败', 'error');
            } finally {
                hideLoader();
            }
        }

        // 处理按钮点击
        function handleAction() {
            const currentIndex = {{ current_index }};
            currentIndex < total - 1 ? loadNextQuestion() : submitGame();
        }

        // 回车提交答案
        document.getElementById('answer').addEventListener('keypress', (e) => {
            if (e.key === 'Enter') checkAnswer(e);
        });
    </script>
</body>
</html>
